<template>
  <div class="window-height window-width row justify-center items-center">
    <div class="column q-pa-lg">
      <div class="row">
        登录中...
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useQuasar } from 'quasar'
import { api } from 'src/boot/axios'
import { useStore } from 'stores/default'

const router = useRouter()
const route = useRoute()
const $q = useQuasar()
const store = useStore()
// 处理SSO回调
onMounted(async () => {
  const code = route.query.code
  if (code) {
    try {
      const response = await api.get('/api/auth/login', {
        params: { code }
      })
      
      if (response.data.code === 200) {
        // 保存token和用户信息
        localStorage.setItem('token', response.data.data.token)
        // 更新store中的用户信息
        store.setUserInfo(response.data.data.user_info)
        
        // 显示成功提示
        $q.notify({
          type: 'positive',
          message: '登录成功'
        })

        // 跳转到首页
        router.push('/')
      } else {
        throw new Error(response.data.message)
      }
    } catch (error) {
      $q.notify({
        type: 'negative',
        message: error.message || '登录失败'
      })
      // 登录失败，跳转到登录页（不带参数）
      router.replace('/auth/login')
    }
  }else{
    try {
        const response = await api.post('/api/auth/login', {
        })

        if (response.data.code === 302) {
        // SSO登录重定向
        window.location.href = response.data.data.redirect_url
        return
        }

        // 在登录成功的两处地方都替换为：
        if (response.data.code === 200) {
        // 保存token
        localStorage.setItem('token', response.data.data.token)
        // 更新store中的用户信息
        store.setUserInfo(response.data.data.user_info)
        
        // 显示成功提示
        $q.notify({
          type: 'positive',
          message: '登录成功'
        })
        
        // 跳转到首页
        router.push('/')
        } else {
        throw new Error(response.data.message)
        }
    } catch (error) {
        $q.notify({
        type: 'negative',
        message: error.message || '登录失败'
        })
    }
  }
})


</script>

<style lang="scss" scoped>
.q-card {
  border-radius: 8px;
}
</style>